package com.vidmt.api.modules.sys.providers.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import com.vidmt.api.common.utils.CommUtil;
import com.vidmt.api.modules.sys.providers.ResProvider;
import com.vidmt.api.modules.sys.utils.PropUtil;

@Service
public class FileResProvider implements ResProvider {
	private static String getStaticDir() {
		return PropUtil.get(PropUtil.KEY_SYS_USER_FILE_DIR);
	}

	@Override
	public void uploadFile(String relpath, InputStream ins) throws IOException {
		OutputStream os = null;
		try {
			File f = new File(getStaticDir(), relpath);
			if (!f.getParentFile().exists()) {
				f.getParentFile().mkdirs();
			}
			os = new FileOutputStream(f);
			FileCopyUtils.copy(ins, os);
		} finally {
			CommUtil.close(os);
		}
	}

	@Override
	public byte[] downloadFile(String relpath) throws IOException {
		File file = new File(getStaticDir(), relpath);
		if (!file.exists()) {
			throw new FileNotFoundException(file.getAbsolutePath());
		} else {
			return FileUtils.readFileToByteArray(file);
		}
	}

	@Override
	public void deleteFile(String relpath) throws IOException {
		File file = new File(getStaticDir(), relpath);
		if (!file.exists()) {
			return;
		}
		if (file.isDirectory()) {
			FileUtils.deleteDirectory(file);
		} else {
			file.delete();
		}
	}
}
